package be.novelfaces.webdriver;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import be.novelfaces.showcase.webdriver.util.Browser;

public final class WebDriverManager {
	
	private static FirefoxDriver FIREFOX_DRIVER;
	private static InternetExplorerDriver INTERNET_EXPLORER_DRIVER;
	private static ChromeDriver CHROME_DRIVER;
	
	private static WebDriver driver;
	
	private WebDriverManager() {
		throw new UnsupportedOperationException("Webdriver manager cannot be instantiated");
	}
	
	public static void initWebDriver(Browser browser){
		if(driver == null) {
			Runtime.getRuntime().addShutdownHook(new Thread() {

				@Override
				public void run() {
					WebDriverManager.closeDrivers();
				}

			});
		}
		if(Browser.INTERNET_EXPLORER.equals(browser)){
			driver = getInternetExplorerDriver();
		} else if(Browser.CHROME.equals(browser)){
			driver =  getChromeDriver();
		} else {
			driver = getFirefoxDriver();
		}
	}

	private static FirefoxDriver getFirefoxDriver() {
		if(FIREFOX_DRIVER == null) {
			FIREFOX_DRIVER = new FirefoxDriver();
		}
		return FIREFOX_DRIVER;
	}
	private static ChromeDriver getChromeDriver() {
		if(CHROME_DRIVER == null) {
			CHROME_DRIVER = new ChromeDriver();
		}
		return CHROME_DRIVER;
	}

	private static InternetExplorerDriver getInternetExplorerDriver() {
		if(INTERNET_EXPLORER_DRIVER == null){
			INTERNET_EXPLORER_DRIVER = new InternetExplorerDriver();
		}
		return INTERNET_EXPLORER_DRIVER;
	}
	
	public static void closeDrivers(){
		if (FIREFOX_DRIVER != null) {
			FIREFOX_DRIVER.close();
		}
		if (INTERNET_EXPLORER_DRIVER != null) {
			INTERNET_EXPLORER_DRIVER.close();
		}
		if (CHROME_DRIVER != null) {
			CHROME_DRIVER.close();
		}
	}
	
	public static WebDriver getWebdriver() {
		return WebDriverManager.driver;
	}

}
